import 'dart:io';

import 'package:path_provider/path_provider.dart';

class FileUtil {
  /// 应用目录
  Future<String> _appDir() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    return appDocDir.path;
  }

  /// 判断文件是否存在
  Future<bool> exists(String fileName) async {
    String path = await _appDir() + fileName;
    File file = File(path);
    return file.exists();
  }

  /// 文件覆盖写入
  Future<String> write(String fileName, List<int> data) async {
    String path = await _appDir() + fileName;
    File file = File(path);
    file.writeAsBytes(data);
    return path;
  }

  /// 文件追加内容
  Future<String> append(String fileName, List<int> data) async {
    String path = await _appDir() + fileName;
    File file = File(path);
    file.writeAsBytes(data, mode: FileMode.append);
    return path;
  }

  /// 文件读取
  Future<List<int>?> read(String fileName) async {
    try {
      File file = File(await _appDir() + fileName);
      return await file.readAsBytes();
    } catch (e) {
      print(e);
      return null;
    }
  }
}
